package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {


    @Autowired
    private ClazzService clazzService;

    /**
     * 分页查询
     * @param student
     * @return
     */
    @Override
    public PageResult<Student> getPageResult(StudentQueryParam student) {
        //1.设置分页查询条件
        Page<Student> page = Page.of(student.getPage(), student.getPageSize());
        //2.开启分页查询
         //2.1创建查询构造器
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(student.getName()), Student::getName, student.getName())
                .eq(student.getDegree() != null, Student::getDegree, student.getDegree())
                .eq(student.getClazzId() != null, Student::getClazzId, student.getClazzId());


        //修改时间倒序排序
        page.addOrder(OrderItem.desc("update_time"));
        //3.调用page()进行分页查询
        page = page(page, queryWrapper);

        //获取学员集合
        List<Student> studentList = page.getRecords();

        //4.获取班级名称
            //获取班级id 去重
        Set<Integer> clazzIds = studentList.stream().map(Student::getClazzId).collect(Collectors.toSet());
        //根据班级ID查询班级
        if (!clazzIds.isEmpty()) {
            List<Clazz> clazzes = clazzService.listByIds(clazzIds);

            //把班级名称设置到学员表中
            Map<Integer, String> clazzMap = clazzes.stream().collect(Collectors.toMap(Clazz::getId, Clazz::getName));
            //遍历studentList
            studentList.forEach(stu -> {
                stu.setClazzName(clazzMap.getOrDefault(stu.getClazzId(), null));
            });
        }


        return new PageResult<>(page.getTotal(),studentList);
    }

    /**
     * 保存学员
     * @param student
     */
    @Override
    public void saveStudent(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        save(student);
    }

    /**
     * 更新学员
     * @param student
     */
    @Override
    public void updateStudent(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        updateById(student);
    }

    /**
     * 处理违纪
     * @param id
     * @param score
     */
    @Override
    public void handleViolation(Integer id, Integer score) {
        //获取到student对象,  根据id查询
        Student student = getById(id);
        //判断学员是否为空
        if (student == null) {
            throw new RuntimeException("学员不存在");
        }
        //违纪次数 +1
        student.setViolationCount((short)(student.getViolationCount() + 1));
        //违纪分值 +score
        student.setViolationScore((short)(student.getViolationScore() + score));

        //更新student对象
        updateById(student);
    }
}
